#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <getopt.h>
#include <unistd.h>
#include <mpi.h>

int SIZE_FILE_NAME = 200;
int SIZE_FILE_LIST = 10000;

char *l_opt_arg;
char* const short_options = "hRL:";
struct option long_options[] ={
  {"help",0,NULL,'h'},
  {"read_in_memory",0,NULL,'R'},
  {"splib",1,NULL,'L'},
  {0,0,0,0},
};

int main(int argc, char* argv[]){
  
  int c;
  char search_options[100];
  char fileNames[SIZE_FILE_LIST][SIZE_FILE_NAME];
  memset(search_options,'\0',sizeof(search_options));
  memset(fileNames,'\0',sizeof(fileNames));
  int fileNum = 0;
  while((c = getopt_long(argc,argv,short_options,long_options, NULL))!= -1){
    switch (c){
    case 'R':
      //printf("search_option:read all in memory. -sR \n");
      strcat(search_options," -sR");
      break;
    case 'L':
      l_opt_arg = optarg;
      //printf("search_option: %s\n",l_opt_arg);
      strcat(search_options, " -sL");
      strcat(search_options, l_opt_arg);
      break;
    case 'h':
      printf("Usage:mpiexec -n 5 mpi_program [-R] -L /path/spectra.splib *.mzXML\n");
      //return 0;
      break;
    default:
      printf("invalid parameter: %c\n",c);
    }
    int opt = optind;

    while((opt < argc)&&(fileNum < SIZE_FILE_LIST)){
      if (argv[opt][0]!='-'){
	//printf("fileName:%s\n",argv[opt]);
	strcpy(fileNames[fileNum],argv[opt]);
	opt++;
	fileNum++;
      }else{
	break;
      }	
    }
    if (fileNum >= SIZE_FILE_LIST){
      printf("WARNING:Only the first %d files are searched!",SIZE_FILE_LIST);
    }
  }
  
  int myid, numproc;  
  MPI_Init(&argc,&argv);
  MPI_Comm_rank(MPI_COMM_WORLD, &myid);
  MPI_Comm_size(MPI_COMM_WORLD, &numproc);
  int blockSize = (fileNum / numproc);
  int remain= (fileNum % numproc);
  int i;
  char queryFn[1000];
  memset(queryFn,'\0',sizeof(queryFn));
  char command[1500] = "spectrast ";
  int start = 0;
  int end = 0;
  if (myid < remain){
    printf("jobsNum=%d, myid=%d, numproc=%d\n",blockSize+1,myid,numproc);
    start = myid * (blockSize + 1);
    end = start + blockSize + 1;
  }else{
    printf("jobsNum=%d, myid=%d, numproc=%d\n",blockSize,myid,numproc);
    if (blockSize == 0){
      //doNothing!
      start = -1;
      end = -1;
    }else{
      start = (myid - remain)*blockSize + remain * （blockSize+1）;
      end = start + blockSize;
    }
  }
  
  for (i = start; i < end; i++){
    strcat(queryFn, " ");
    strcat(queryFn,fileNames[i]);
  }
  
  strcat(command,search_options);
  strcat(command,queryFn);
  printf ("start=%d,end=%d\n",start,end);
  if (end != -1){
    //puts(command);
    system(command);
  }
  MPI_Finalize();
}
